<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="140px"
      v-loading="formLoading"
    >
      <el-form-item label="平台编号" prop="platformId">
        <el-input v-model="formData.platformId" placeholder="请输入平台编号" />
      </el-form-item>
      <el-form-item label="店铺代码" prop="code">
        <el-input v-model="formData.code" placeholder="请输入店铺代码" />
      </el-form-item>
      <el-form-item label="店铺名称" prop="name">
        <el-input v-model="formData.name" placeholder="请输入店铺名称" />
      </el-form-item>
      <el-form-item label="英文名称" prop="nameEn">
        <el-input v-model="formData.nameEn" placeholder="请输入英文名称" />
      </el-form-item>
      <el-form-item label="店铺类型" prop="type">
        <el-select v-model="formData.type" placeholder="请选择店铺类型">
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.CROSSBORDER_STORE_TYPE)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="平台店铺ID" prop="platformStoreId">
        <el-input v-model="formData.platformStoreId" placeholder="请输入平台店铺ID" />
      </el-form-item>
      <el-form-item label="卖家ID" prop="sellerId">
        <el-input v-model="formData.sellerId" placeholder="请输入卖家ID" />
      </el-form-item>
      <el-form-item label="市场ID" prop="marketplaceId">
        <el-input v-model="formData.marketplaceId" placeholder="请输入市场ID" />
      </el-form-item>
      <el-form-item label="店铺链接" prop="storeUrl">
        <el-input v-model="formData.storeUrl" placeholder="请输入店铺链接" />
      </el-form-item>
      <el-form-item label="区域代码" prop="region">
        <el-input v-model="formData.region" placeholder="请输入区域代码" />
      </el-form-item>
      <el-form-item label="主要货币" prop="currency">
        <el-input v-model="formData.currency" placeholder="请输入主要货币" />
      </el-form-item>
      <el-form-item label="主要语言" prop="language">
        <el-input v-model="formData.language" placeholder="请输入主要语言" />
      </el-form-item>
      <el-form-item label="时区" prop="timezone">
        <el-input v-model="formData.timezone" placeholder="请输入时区" />
      </el-form-item>
      <el-form-item label="联系人" prop="contactPerson">
        <el-input v-model="formData.contactPerson" placeholder="请输入联系人" />
      </el-form-item>
      <el-form-item label="联系电话" prop="contactPhone">
        <el-input v-model="formData.contactPhone" placeholder="请输入联系电话" />
      </el-form-item>
      <el-form-item label="联系邮箱" prop="contactEmail">
        <el-input v-model="formData.contactEmail" placeholder="请输入联系邮箱" />
      </el-form-item>
      <el-form-item label="营业执照号" prop="businessLicense">
        <el-input v-model="formData.businessLicense" placeholder="请输入营业执照号" />
      </el-form-item>
      <el-form-item label="税号" prop="taxNumber">
        <el-input v-model="formData.taxNumber" placeholder="请输入税号" />
      </el-form-item>
      <el-form-item label="授权状态" prop="authStatus">
        <el-select v-model="formData.authStatus" placeholder="请选择授权状态">
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.CROSSBORDER_AUTH_STATUS)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="授权时间" prop="authTime">
        <el-date-picker
          v-model="formData.authTime"
          type="date"
          value-format="x"
          placeholder="选择授权时间"
        />
      </el-form-item>
      <el-form-item label="授权过期时间" prop="authExpireTime">
        <el-date-picker
          v-model="formData.authExpireTime"
          type="date"
          value-format="x"
          placeholder="选择授权过期时间"
        />
      </el-form-item>
      <el-form-item label="最后同步时间" prop="lastSyncTime">
        <el-date-picker
          v-model="formData.lastSyncTime"
          type="date"
          value-format="x"
          placeholder="选择最后同步时间"
        />
      </el-form-item>
      <el-form-item label="同步状态" prop="syncStatus">
        <el-select v-model="formData.syncStatus" placeholder="请选择同步状态">
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.CROSSBORDER_SYNC_STATUS)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="同步错误信息" prop="syncErrorMsg">
        <el-input v-model="formData.syncErrorMsg" placeholder="请输入同步错误信息" />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="formData.status" placeholder="请选择状态">
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.CROSSBORDER_COMMON_STATUS)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="是否启用" prop="enabled">
        <el-select v-model="formData.enabled" placeholder="请选择是否启用">
          <el-option
            v-for="dict in getBoolDictOptions(DICT_TYPE.INFRA_BOOLEAN_STRING)"
            :key="String(dict.value)"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="排序" prop="sort">
        <el-input v-model="formData.sort" placeholder="请输入排序" />
      </el-form-item>
      <el-form-item label="备注" prop="remark">
        <el-input v-model="formData.remark" placeholder="请输入备注" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { DICT_TYPE, getIntDictOptions, getBoolDictOptions } from '@/utils/dict'
import { PlatformStoreApi, PlatformStoreVO } from '@/api/crossborder/platformstore'

/** 跨境电商店铺管理 表单 */
defineOptions({ name: 'PlatformStoreForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  platformId: undefined,
  code: undefined,
  name: undefined,
  nameEn: undefined,
  type: undefined,
  platformStoreId: undefined,
  sellerId: undefined,
  marketplaceId: undefined,
  storeUrl: undefined,
  region: undefined,
  currency: undefined,
  language: undefined,
  timezone: undefined,
  contactPerson: undefined,
  contactPhone: undefined,
  contactEmail: undefined,
  businessLicense: undefined,
  taxNumber: undefined,
  authStatus: undefined,
  authTime: undefined,
  authExpireTime: undefined,
  lastSyncTime: undefined,
  syncStatus: undefined,
  syncErrorMsg: undefined,
  status: undefined,
  enabled: undefined,
  sort: undefined,
  remark: undefined,
})
const formRules = reactive({
  platformId: [{ required: true, message: '平台编号不能为空', trigger: 'blur' }],
  code: [{ required: true, message: '店铺代码不能为空', trigger: 'blur' }],
  name: [{ required: true, message: '店铺名称不能为空', trigger: 'blur' }],
  type: [{ required: true, message: '店铺类型（1个人店铺 2企业店铺 3品牌店铺）不能为空', trigger: 'change' }],
  platformStoreId: [{ required: true, message: '平台店铺ID不能为空', trigger: 'blur' }],
  authStatus: [{ required: true, message: '授权状态（0未授权 1已授权 2授权过期 3授权失败）不能为空', trigger: 'blur' }],
  syncStatus: [{ required: true, message: '同步状态（0未同步 1同步中 2同步成功 3同步失败）不能为空', trigger: 'blur' }],
  status: [{ required: true, message: '状态（0正常 1停用）不能为空', trigger: 'blur' }],
  enabled: [{ required: true, message: '是否启用不能为空', trigger: 'blur' }],
  sort: [{ required: true, message: '排序不能为空', trigger: 'blur' }],
})
const formRef = ref() // 表单 Ref

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await PlatformStoreApi.getPlatformStore(id)
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as PlatformStoreVO
    if (formType.value === 'create') {
      await PlatformStoreApi.createPlatformStore(data)
      message.success(t('common.createSuccess'))
    } else {
      await PlatformStoreApi.updatePlatformStore(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    platformId: undefined,
    code: undefined,
    name: undefined,
    nameEn: undefined,
    type: undefined,
    platformStoreId: undefined,
    sellerId: undefined,
    marketplaceId: undefined,
    storeUrl: undefined,
    region: undefined,
    currency: undefined,
    language: undefined,
    timezone: undefined,
    contactPerson: undefined,
    contactPhone: undefined,
    contactEmail: undefined,
    businessLicense: undefined,
    taxNumber: undefined,
    authStatus: undefined,
    authTime: undefined,
    authExpireTime: undefined,
    lastSyncTime: undefined,
    syncStatus: undefined,
    syncErrorMsg: undefined,
    status: undefined,
    enabled: undefined,
    sort: undefined,
    remark: undefined,
  }
  formRef.value?.resetFields()
}
</script>